package yr.website

import grails.converters.JSON
import grails.transaction.Transactional
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class ManagerController {
    def managerService
    static final Logger logger = LoggerFactory.getLogger(ManagerController.class)

    @Transactional
    def refresh() {
        def data = [:]
        def username = "${params.account}"
        def oldPassword = "${params.oldPassword}"
        def newPassword = "${params.newPassword}"
        try {
            def manager = Manager.findByAccountAndPassword(username, managerService.getMD5(oldPassword))
            if (manager) {
                manager.password = managerService.getMD5(newPassword)
                manager.save()
                data << [statuCode: "0", errMsg: "0"]
                render data as JSON
            } else {
                data << [statuCode: "1", errMsg: "1"]
                render data as JSON
            }
        } catch (Exception e) {
            logger.error("ManagerController -- refresh Exception " + e.message)
        }
    }

    def loginout() {
        def data = [:]
        try {
            session.invalidate()
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            logger.error("ManagerController -- loginout Exception " + e.message)
        }
    }

    /**
     * 后台登录验证
     */
    def vali() {
        def data = [:]
        def username = "${params.username}"
        def password = "${params.password}"
        try {
            Manager manager = Manager.findByAccountAndPassword(username, managerService.getMD5(password))
            if (manager == null) {
                def u = Manager.findByAccount(username)
                data << [statuCode: "1", errMsg: "1"]
            } else {
                if (manager.state == true) {
                    session.setAttribute("username", manager.account)
                    session.manager = manager.account
                    session.setMaxInactiveInterval(60 * 60 * 2)
                    new Logg(recordor: manager.account, recordDate: new Date(), type: "登录操作").save()
                    data << [statuCode: "0", errMsg: "0", codeState: "0", data: manager.account]
                } else {
                    data << [statuCode: "2", errMsg: "2"]
                }
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("ManagerController -- vali Exception " + e.message)
        }
    }

    def getAll() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def account = "${params.acc ?: ''}"
        def name = "${params.name ?: ''}"
        def m = 1
        def c = m.longValue()
        try {
            def a = Manager.createCriteria()
            def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
                and {
                    if (!account.isEmpty()) {
                        eq("account", account)
                    }
                    if (!name.isEmpty()) {
                        eq("name", name)
                    }
                    not { 'in'("id", c) }
                }
            }
            def b = Manager.createCriteria()
            def total = b.get {
                and {
                    if (!account.isEmpty()) {
                        eq("account", account)
                    }
                    if (!name.isEmpty()) {
                        eq("name", name)
                    }
                    not { 'in'("id", c) }
                }
                projections {
                    count("account")
                }
            }
            if (list) {
                data << [statuCode: "0", errMsg: "0", data: list, total: total]
            } else {
                data << [statuCode: "1", errMsg: "1"]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("ManagerController -- getAll Exception " + e.message)
        }
    }

    def add() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def account = "${params.account ?: ''}"
        try {
            def user = Manager.findByAccount(account)
            if (user) {
                data << [statuCode: "1", errMsg: "1"]
            } else {
                def users = new Manager()
                bindData(users, params, [exclude: ['page', 'pagesize']])
                users.state = true
                users.password = managerService.getMD5("123456")
                users.createDate = new Date()
                def length = User.count()
                managerService.add(users)
                def list = Manager.list(max: pagesize, offset: (page - 1) * pagesize)
                def total = Manager.count()
                new Logg(recordor: session.getAttribute("username"), recordDate: new Date(), type: "添加权限用户 " + account).save()
                data << [statuCode: "0", errMsg: "0", data: list, total: total]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("ManagerController -- add Exception" + e.message)
        }
    }

    def sa() {
        def data = [:]
        def account = "${params.account ?: ''}"
        def state = "${params.state ?: ''}"
        try {
            def user = Manager.findByAccount(account)
            if (state == "false") {
                user.state = false
            } else {
                user.state = true
            }
            managerService.add(user)
            new Logg(recordor: session.getAttribute("username"), recordDate: new Date(), type: "修改" + account + "的权限状态").save()
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- sa Exception " + e.message)
        }
    }

    def reset() {
        def data = [:]
        def id = Integer.parseInt("${params.id}")
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        try {
            def user = Manager.findById(id)
            user.password = managerService.getMD5("123456")
            if (managerService.add(user)) {
                def list = Manager.list(max: pagesize, offset: (page - 1) * pagesize)
                def total = Manager.count()
                new Logg(recordor: session.getAttribute("username"), recordDate: new Date(), type: "重置 " + user.account + " 登录密码").save()
                data << [statuCode: "0", errMsg: "0", data: list, total: total]
            } else {
                data << [statuCode: "1", errMsg: "1"]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("ManagerController -- reset Exception " + e.message)
        }
    }
}
